import {
  showLoading,
  hideLoading,
  showNoNetwork,
  showError,
  showMsg,
  showSuccess,
} from '@/utils/toast'

module.exports.call = function (obj) {
  var path, method, params, data
  if (typeof obj === 'string') {
    path = obj
    method = 'GET'
  } else {
    path = obj.path
    method = obj.method
    params = obj.params
    data = obj.data
  }

  return new Promise((resolve, reject) => {
    wx.cloud.callContainer({
      path: path + handleParams(params),
      method,
      data,
      header: {
        'X-WX-SERVICE': 'springboot-svdq', // xxx中填入服务名称（微信云托管 - 服务管理 - 服务列表 - 服务名称）
        'content-type': 'application/json',
      },
      success: ({ data: { code, msg, data } }) => {
        if (code === 0) {
          return resolve(data)
        }
        let duration;
        if (code === 1) {
          hideLoading()
          wx.showModal({
            content: msg,
            showCancel: false
          })
        } else if (code === 2) {
          duration = showMsg(msg)
        } else {
          duration = showMsg("服务器异常~")
        }
        reject(duration)
      },
      fail: err => {
        const duration = showMsg('服务器异常！')
        reject(duration)
      },
    })

  //   wx.request({
  //     url: 'http://127.0.0.1:80' + path + handleParams(params),
  //     method,
  //     data,
  //     header: {
  //       'X-WX-OPENID': 'o7cql7eoiPHvRCq670i-lqU5aQog',
  //       'X-Forwarded-For': '176.86.4.6',
  //     },
  //     success: ({ data: { code, msg, data } }) => {
  //       if (code === 0) {
  //         return resolve(data)
  //       }
  //       let duration;
  //       if (code === 1) {
  //         hideLoading()
  //         wx.showModal({
  //           content: msg,
  //           showCancel: false
  //         })
  //       } else if (code === 2) {
  //         duration = showMsg(msg)
  //       } else {
  //         duration = showMsg("服务器异常~")
  //       }
  //       reject(duration)
  //     },
  //     fail: err => {
  //       const duration = showMsg('服务器异常！')
  //       reject(duration)
  //     },
  //   })
  })
}

function handleParams(o) {
  if (!o) {
    return ''
  }
  let arr = []
  for (let k in o) {
    arr.push(k + '=' + o[k])
  }
  return '?' + arr.join('&')
}
